﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LinqToLdap;
using System.Configuration;

namespace LINQtoLDAPDemo_ConnectionPoolExample
{
    class Program
    {
        private const int COUNT = 5;

        static void Main(string[] args)
        {
            SetupLDAPConfigurationWithMaxPoolSizeofOne();

            User[] managers;
            using (var ldapContext = new DirectoryContext())
            {
                managers = ldapContext.Query<User>().Where(u => u.Manager == null || u.Manager == "").Take(5).ToArray();

                PrintManagerRoster(managers); // We will exceed pool factory size here.
            }

            PrintManagerRoster(managers); // We will not exceed pool factory size here.

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }

        private static void PrintManagerRoster(User[] managers)
        {
            foreach (User boss in managers)
            {
                Console.WriteLine(string.Format("{0} {1}:", boss.FirstName, boss.LastName));
                User[] employees = GetEmployeesByManagerDN(boss.Manager);
                PrintMinionRoster(employees);
            }
        }

        private static void PrintMinionRoster(User[] employees)
        {
            if (employees != null)
            {
                foreach (User minion in employees)
                {
                    Console.WriteLine(string.Format("\t{0} {1}", minion.FirstName, minion.LastName));
                }
            }
        }

        private static void SetupLDAPConfigurationWithMaxPoolSizeofOne()
        {
            LdapConfiguration _configuration = new LinqToLdap.LdapConfiguration();
            _configuration.ConfigurePooledFactory(ConfigurationManager.AppSettings["computerName"]).MaxPoolSizeIs(1);
            _configuration.AddMapping(new UserMapping());
            _configuration.AddMapping(new GroupMapping());
            _configuration.UseStaticStorage();
        }

        private static User[] GetEmployeesByManagerDN(string managerDN)
        {
            User[] managersMinions = null;

            try
            {
                using (var ldapContext = new DirectoryContext())
                {
                    managersMinions = ldapContext.Query<User>().Where(u => u.Manager.Equals(managerDN)).Take(COUNT).ToArray();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return managersMinions;
        }
    }
}
